package com.gagakuai.bpm.domian.events;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.gagakuai.bpm.common.constants.BpmInsActConstants;
import com.gagakuai.bpm.dao.mapper.camunda.ActHiActinstMapper;
import com.gagakuai.bpm.dao.mapper.camunda.WorkFlowTaskNodeMapper;
import com.gagakuai.bpm.domian.entity.camuda.ActHiActinst;
import com.gagakuai.bpm.utils.IDgenerateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

/*
 * @program: bpm_server
 * @description: 拒绝事件监听器
 * @author: houhong
 * @create: 2022-07-07 16:41
 */
@Slf4j
@Component
public class RejectTaskListener implements ApplicationListener<RejectTaskEvent> {


    @Autowired
    private ActHiActinstMapper actHiActinstMapper;


    @Autowired
    private WorkFlowTaskNodeMapper workFlowTaskNodeMapper;

    @Override
    public void onApplicationEvent(RejectTaskEvent rejectTaskEvent) {

        log.info("=====处理拒绝任务后无结束标志=====");
        RejectTaskEvent.RejectTaskEventEventData rejectTaskEventEventData = rejectTaskEvent.getEventData();
        String processId = rejectTaskEventEventData.getProcessId();
        IPage<ActHiActinst> page = new Page<>(1, 200);
        try {
            IPage<ActHiActinst> actHiActinstIPage = workFlowTaskNodeMapper.selectWorkflowNoByProcessOorderByEndIdPage(page, null, processId);
            List<ActHiActinst> actHiActinsts = actHiActinstIPage.getRecords();
            Boolean hasEnd = actHiActinsts.stream().map(ActHiActinst::getActInstState)
                    .anyMatch(curState -> curState.equals(1));

            if (!hasEnd) {
                log.info("不存在结束任务，需要人为添加一条");
                //降序
                actHiActinsts = actHiActinsts.stream().sorted((p1, p2) -> p2.getEndTime().compareTo(p1.getEndTime()))
                        .collect(Collectors.toList());


                ActHiActinst acHi = actHiActinsts.get(0);
                acHi.setId(IDgenerateUtils.nextIdStr());
                acHi.setTaskId(null);
                acHi.setStartTime(new Timestamp(System.currentTimeMillis() + 10000l));
                acHi.setEndTime(new Timestamp(System.currentTimeMillis() + 10000l));
                acHi.setAssignee(null);
                acHi.setProcInstId(IDgenerateUtils.nextIdStr());
                acHi.setActName("审批不通过");
                acHi.setActType("end");
                acHi.setActInstState(BpmInsActConstants.HAS_FINISEND);
                actHiActinstMapper.insertSelective(acHi);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}